#!/usr/bin/env python3
# -*- coding:utf-8 -*-
## author : mike
## date   : 2014.12.4
"""
"""

import os 
import sys
from os.path import realpath, dirname, basename, isdir

sys.path.append(dirname(dirname(realpath(__file__))))
from xbc3.fileio import FileIO

class CountDifferentTimes(object):
    """docstring for CountDifferentTimes"""
    def __init__(self, *inputfiles):
        super(CountDifferentTimes, self).__init__()

        self.files_name = []
        for fn in inputfiles:
            if isdir(fn):
                continue
            if 'sys_ss' in  basename(fn):
                self.files_name.append(fn)
        if not self.files_name:
            print('Error:can not find sys_ss files!!!\n', file=sys.stderr)
            sys.exit()
        self.cookie_dict = {}
        self.times_dict={}

    def cookie_by_times(self, filename):
        """"""
        file = FileIO(filename)
        print(filename,"\n")
        for line in file:  
            try:
                cookie = line[44:76]
                times =int(line[83:line.find('|user')])
            except Exception as e:
                pass
            if cookie in self.cookie_dict:
                if self.cookie_dict[cookie]<times:
                    self.cookie_dict[cookie]=times
                else:
                    pass
            else:
                self.cookie_dict[cookie]=times

        sys.stdout.write('%s finished' % (filename))   

    def count_times(self,cookie_dict):
        for i in cookie_dict.values():
            if i in self.times_dict:
                self.times_dict[i]+=1
            else:
                self.times_dict[i]=1

    def output(self):
        """"""
        fpath=os.path.split(self.files_name[0])[0]
        result_path=os.path.join(fpath,'result.csv')
        
        with FileIO(result_path,'w') as f:
            f.write('times,number\n')
            for k in sorted(self.times_dict, key=lambda x:self.times_dict[x]):
                v = self.times_dict[k]
                f.write('%s, %d\n' % (k, v))

    def run(self):
        """"""
        for fn in self.files_name:
            self.cookie_by_times(fn)
        self.count_times(self.cookie_dict)
        self.output()
        

if __name__ == '__main__':
    '''driver'''
    inputfiles = []
    for line in sys.stdin:
        line = line.rstrip('\r\n')
        inputfiles.append(line)
    print(inputfiles)
    cdt=CountDifferentTimes(*inputfiles)
    cdt.run()
